package com.antdesignbackend.backend.form.saleDeclarationB.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Enterprise;
import com.antdesignbackend.backend.entity.Production;
import com.antdesignbackend.backend.service.EnterpriseService;
import com.antdesignbackend.backend.service.ProductionService;
import com.antdesignbackend.backend.situationReport.entity.SituationReport;
import com.antdesignbackend.backend.situationReport.service.SituationReportService;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.form.saleDeclarationB.entity.SaleDeclarationB;
import com.antdesignbackend.backend.form.saleDeclarationB.entity.entityVo.SaleDeclarationBVo;
import com.antdesignbackend.backend.form.saleDeclarationB.service.SaleDeclarationBService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 跨省销售用产地检疫申报单(动物B)
 *
 * @author 林宇杰
 * @email saleDeclarationB
 * @date 2020-08-14 09:55:43
 */

@Controller
@RequestMapping("/saleDeclarationB")
@Slf4j
public class SaleDeclarationBController extends BaseController{

	private static final String FUN_NAME = "跨省销售用产地检疫申报单(动物B)";//功能名称

	@Autowired
	private SaleDeclarationBService saleDeclarationBService;
	@Autowired
	private EnterpriseService enterpriseService;
	@Autowired
	private ProductionService productionService;
	@Autowired
	private SituationReportService situationReportService;


	@GetMapping("/index")
	@AuthToken
	public String index(Model model) {
		Enterprise enterprise=enterpriseService.getById(getLoginEnterpriseId());
		model.addAttribute("enterprise",enterprise);
		Integer animalType=getLoginAnimalTypes();
		model.addAttribute("animalType",animalType);
		return "form/saleDeclarationB/index";
	}

	/**
	 * 审批
	 * @return
	 */
	@GetMapping("/approval")
	@AuthToken
	public String approval() {
		return "form/saleDeclarationB/approval";
	}


	@PostMapping("/tableSearch")
	@ResponseBody
	ReturnVO tableSearch(@RequestBody SaleDeclarationBVo saleDeclarationBVo) throws SecurityException, IllegalArgumentException{
		ReturnVO result = new ReturnVO();
		List<SaleDeclarationB> saleDeclarationBS = new ArrayList<>();
		QueryWrapper<SaleDeclarationB> wrapper = new QueryWrapper<>();
		if (saleDeclarationBVo.getTypes() != null){
			wrapper.eq("types",saleDeclarationBVo.getTypes());
		}
		if (saleDeclarationBVo.getTimeInterval() != null && !saleDeclarationBVo.getTimeInterval().equals("")) {
			String[] str = saleDeclarationBVo.getTimeInterval().split(" - ");
			String star = str[0];
			String end = str[1];
			wrapper.between("saleDate", star, end);
		}
		if ("2".equals(getUserType())){
		}else if ("3".equals(getUserType())){
			wrapper.eq("eid",getLoginEnterpriseId());
		}else {
			wrapper.eq("eid",0);
		}
		wrapper.orderByDesc("saleDate");
		//先统计满足条件的数据总数，因为sql 不包括排序
		int total = saleDeclarationBService.count(wrapper);
		result.setTotal(total);
		System.out.println("*******************************满足条件的数据有：" + total);
		//再查询
		if (total >= 0) {

			saleDeclarationBS = saleDeclarationBService.page(new Page<SaleDeclarationB>(saleDeclarationBVo.getPageIndex(), saleDeclarationBVo.getPageSize()), wrapper).getRecords();
			for (SaleDeclarationB saleDeclarationB : saleDeclarationBS) {

				if(saleDeclarationB.getAnimalPhoto()!=null && !saleDeclarationB.getAnimalPhoto().equals("")){
					saleDeclarationB.setAnimalPhoto(WebConfig.host + "images/" + saleDeclarationB.getAnimalPhoto());
				}
				if(saleDeclarationB.getCarPhoto()!=null && !saleDeclarationB.getCarPhoto().equals("")){
					saleDeclarationB.setCarPhoto(WebConfig.host + "images/" + saleDeclarationB.getCarPhoto());
				}
				if(saleDeclarationB.getPigCarPhoto()!=null && !saleDeclarationB.getPigCarPhoto().equals("")){
					saleDeclarationB.setPigCarPhoto(WebConfig.host + "images/" + saleDeclarationB.getPigCarPhoto());
				}
				if(saleDeclarationB.getReportPhoto()!=null && !saleDeclarationB.getReportPhoto().equals("")){
					saleDeclarationB.setReportPhoto(WebConfig.host + "images/" + saleDeclarationB.getReportPhoto());
				}
				if(saleDeclarationB.getCertificatePhoto()!=null && !saleDeclarationB.getCertificatePhoto().equals("")){
					saleDeclarationB.setCertificatePhoto(WebConfig.host + "images/" + saleDeclarationB.getCertificatePhoto());
				}
				if(saleDeclarationB.getAgriculturePhoto()!=null && !saleDeclarationB.getAgriculturePhoto().equals("")){
					saleDeclarationB.setAgriculturePhoto(WebConfig.host + "images/" + saleDeclarationB.getAgriculturePhoto());
				}
			}
		}
		result.setData(saleDeclarationBS);
		return result;
	}

	@GetMapping("/getById/{id}")
	@ResponseBody
	public	SaleDeclarationB getById(@PathVariable(name = "id") String id) {
		SaleDeclarationB obj = saleDeclarationBService.getById(id);
		return obj;
	}

	@PostMapping("/save")
	@ResponseBody
	public ReturnVO save(@RequestBody SaleDeclarationB saleDeclarationB){
		ReturnVO result = new ReturnVO();
		Date savenDay=getDay();
		QueryWrapper<Production> productionQueryWrapper=new QueryWrapper<>();
//        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
//        String s=simpleDateFormat.format(new Date());
		LocalDate now =LocalDate.now();
		int year=now.getYear();     //获取年
		LocalDate localDate1 = LocalDate.of(year, 12, 15);
		LocalDate localDate2 = LocalDate.of(year, 12, 31);
		LocalDate localDate3 = LocalDate.of(year+1, 1, 1);
		LocalDate localDate4 = LocalDate.of(year+1, 2, 1);

		Boolean b = true;
		productionQueryWrapper.eq("eid",getLoginEnterpriseId()).between("changeTime",savenDay,new Date());
		if(productionService.count(productionQueryWrapper)==0){
			b = false;
			result.setMessage("您已七天以上未更新养殖档案,请及时更新后再提交检疫申报!");
		}else if(now.isAfter(localDate1) && now.isBefore(localDate2)){
			QueryWrapper<SituationReport> situationReportQueryWrapper=new QueryWrapper<>();
			situationReportQueryWrapper.eq("reportYear",year+"-01-01 00:00:00");
			if(situationReportService.count(situationReportQueryWrapper) <= 0){
				result.setMessage("您本年度尚未填写动物防疫条件和防疫制度执行情况报备单,请及时填写!");
			}
		}else if(now.isAfter(localDate3) && now.isBefore(localDate4)){
			QueryWrapper<SituationReport> situationReportQueryWrapper=new QueryWrapper<>();
			situationReportQueryWrapper.eq("reportYear",(year-1)+"-01-01 00:00:00");
			if(situationReportService.count(situationReportQueryWrapper) <= 0){
				result.setMessage("您"+(year-1)+"年尚未填写动物防疫条件和防疫制度执行情况报备单,请及时填写!");
			}
		}else if(now.isAfter(localDate4)){
			QueryWrapper<SituationReport> situationReportQueryWrapper=new QueryWrapper<>();
			situationReportQueryWrapper.eq("reportYear",(year-1)+"-01-01 00:00:00");
			if(situationReportService.count(situationReportQueryWrapper) <= 0){
				b=false;
				result.setMessage("您"+(year-1)+"年尚未填写动物防疫条件和防疫制度执行情况报备单,请填写后操作!");
			}
		}
		if (b){
			saleDeclarationB.setTypes(0);//审批中
			saleDeclarationB.setCreateBy(getLoginUserId());
			saleDeclarationB.setCreateTime(new Date());
			saleDeclarationB.setEid(getLoginEnterpriseId());
			try {
				saleDeclarationBService.save(saleDeclarationB);
			}catch (Exception e){
				result.setMessage("保存失败！");
				result.setCode("500");
			}
		}else {
			result.setCode("500");
		}
		return result;
	}

	@PostMapping("update")
	@ResponseBody
	public ReturnVO updateById(@RequestBody SaleDeclarationB saleDeclarationB){
		ReturnVO result = new ReturnVO();
		saleDeclarationB.setTypes(0);//审批中
		saleDeclarationB.setCreateBy(getLoginUserId());
		saleDeclarationB.setCreateTime(new Date());
		saleDeclarationB.setEid(getLoginEnterpriseId());
		try {
			saleDeclarationBService.updateById(saleDeclarationB);
		}catch (Exception e){
			result.setMessage("保存失败！");
			result.setCode("500");
		}
		return result;
	}

	/**
     * 根据id删除
     */
	@DeleteMapping("/deleteById/{id}")
	@ResponseBody
	public ReturnVO deleteById(@PathVariable Serializable id) {
		ReturnVO result = new ReturnVO();
		if (saleDeclarationBService.removeById(Integer.parseInt(id.toString())) == true) {
			result.setMessage("删除成功");
		} else {
			result.setMessage("删除失败");
			result.setCode("0");
		}
		return result;
	}
	/***
	 * 上传图片
	 * @return
	 */
	@PostMapping("/uploadImages")
	@ResponseBody
	public Map<String,String> uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8") ;
		long random =System.currentTimeMillis();
		String dateKey =random+"";
		String localPathDir="";
		String newFileName="";
		Map<String,String> map = new HashMap<>();
		if(!WebConfig.uploadImage.equals(""))
		{
			localPathDir=WebConfig.uploadImage;
		}
		else
		{
			localPathDir= ResourceUtils.getURL("classpath:").getPath()+"images/";
		}
		File logoSaveFile = new File(localPathDir);
		if(!logoSaveFile.exists()){
			logoSaveFile.mkdirs();
		}
		if (request instanceof MultipartHttpServletRequest) {
			MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
			Iterator iter = mr.getFileMap().values().iterator();
			if (iter.hasNext()) {
				MultipartFile file = (MultipartFile) iter.next();
				String oname = file.getOriginalFilename();
				String fileTyle=oname.substring(oname.lastIndexOf("."),oname.length());
				fileTyle=fileTyle.toLowerCase();
				newFileName=dateKey+fileTyle;
				String fileName = localPathDir+newFileName;
				if(fileTyle.equals(".png") || fileTyle.equals(".gif") || fileTyle.equals(".jpg"))
				{
					File files = new File(fileName);
					InputStream inputstream =file.getInputStream();
					byte[] bytes = new byte[1024];
					FileOutputStream outstream = new FileOutputStream(fileName);
					int index;
					while ((index = inputstream.read(bytes)) != -1) {
						outstream.write(bytes, 0, index);
						outstream.flush();
					}
					outstream.close();
					inputstream.close();
				}
			}
		}
		if(newFileName!=null && !newFileName.equals(""))
		{
			map.put("url",newFileName);
			map.put("httpUrl",WebConfig.host+"images/"+newFileName);
		}
		// System.out.println("return:"+localPathDir+newFileName);
		return map;
	}
	Date getDay(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		Calendar c = Calendar.getInstance();

		c.add(Calendar.DATE, - 7);

		Date monday = c.getTime();

		return monday;
	}

	/**
	 * 审批
	 * @param vo
	 * @return
	 */
	@PostMapping("/action")
	@ResponseBody
	public ReturnVO action(@RequestBody SaleDeclarationBVo vo) {
		ReturnVO result = new ReturnVO();
		Boolean b = false;
		try {
			switch (vo.getAction()){
				case "aproval": //审批
					SaleDeclarationB saleDeclarationB = new SaleDeclarationB();
					saleDeclarationB.setId(vo.getId());
					saleDeclarationB.setTypes(vo.getTypes());
					saleDeclarationB.setOpinion(vo.getOpinion());
					saleDeclarationB.setAprovalTime(new Date());
					saleDeclarationB.setAprovalId(getLoginUserId());
					saleDeclarationB.setAproval(getLoginUserName());
					b = saleDeclarationBService.updateB(saleDeclarationB);
					break;
				case "certificate": //出证
					SaleDeclarationB saleDeclarationB1 = new SaleDeclarationB();
					saleDeclarationB1.setId(vo.getId());
					saleDeclarationB1.setTypes(3);
					saleDeclarationB1.setCertificateId(getLoginUserId());
					saleDeclarationB1.setCertificate(getLoginUserName());
					saleDeclarationB1.setWitness(vo.getWitness());
					saleDeclarationB1.setLivestock(vo.getLivestock());
					saleDeclarationB1.setCertificateTime(new Date());
					b = saleDeclarationBService.updateById(saleDeclarationB1);
					break;
			}
		}catch (Exception e){
			b = false;
		}
		if (!b){
			result.setMessage("操作失败！");
			result.setCode("500");
		}
		return result;
	}
}
